package com.ojoin.weixin.core.oauth2.util;

/**
 * @author Engineer-Jsp
 * @date 2014.10.09
 * 请求数据通用类
 * */
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.json.JSONUtils;
import com.ojoin.weixin.core.model.AccessToken;
import com.ojoin.weixin.core.oauth2.inteceptor.APPConstants;

public class RequestUtil {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(RequestUtil.class);

    /** 
     * 发起https请求并获取结果 
     *  
     * @param requestUrl 请求地址 
     * @param requestMethod 请求方式（GET、POST） 
     * @param outputStr 提交的数据 
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) 
     */  
	public static Map HttpRequest(String request , String RequestMethod , String output ){
		Map jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			//建立连接
			URL url = new URL(request);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod(RequestMethod);
			if(output!=null){
				OutputStream out = connection.getOutputStream();
				out.write(output.getBytes(APPConstants.APP_ENCODING));
				out.close();
			}
			//流处理
			InputStream input = connection.getInputStream();
			InputStreamReader inputReader = new InputStreamReader(input,APPConstants.APP_ENCODING);
			BufferedReader reader = new BufferedReader(inputReader);
			String line;
			while((line=reader.readLine())!=null){
				buffer.append(line);
			}
			//关闭连接、释放资源
			reader.close();
			inputReader.close();
			input.close();
			input = null;
			connection.disconnect();
//			jsonObject = JSONObject.fromObject(buffer.toString());
			jsonObject = JSONUtils.parseObject(buffer.toString(), Map.class);
		} catch (Exception e) {
		}
		return jsonObject;
	} 
//	 获取access_token的接口地址（GET）   
	public final static String access_token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=CorpID&corpsecret=SECRET&debug=1";  
	  
	/** 
	 * 获取access_token 
	 *  
	 * @param CorpID 企业Id 
	 * @param SECRET 管理组的凭证密钥，每个secret代表了对应用、通讯录、接口的不同权限；不同的管理组拥有不同的secret 
	 * @return 
	 */  
	public static AccessToken getAccessToken(String corpID, String secret) {  
	    AccessToken accessToken = null;  
	  
	    String requestUrl = access_token_url.replace("CorpID", corpID).replace("SECRET", secret);  
	    Map jsonObject = HttpRequest(requestUrl, "GET", null);  
	    // 如果请求成功  
	    if (null != jsonObject) {  
	        try {  
	            accessToken = new AccessToken();  
	            accessToken.setToken(jsonObject.get("access_token") + "");  
	            accessToken.setExpiresIn(CommonUtils.getInt(jsonObject.get("expires_in") + ""));
	            System.out.println("获取token成功:"+jsonObject.get("access_token")+"————"+jsonObject.get("expires_in"));
	        } catch (Exception e) {  
	            accessToken = null;  
	            // 获取token失败  
	            String error = String.format("获取token失败 errcode:{} errmsg:{}", jsonObject.get("errcode"), jsonObject.get("errmsg"));  
	            System.out.println(error);
	        }  
	    }  
	    return accessToken;  
	}
	public static String URLEncoder(String str){
		String result = str ;
		try {
		result = java.net.URLEncoder.encode(result,APPConstants.APP_ENCODING);	
		} catch (Exception e) {
        e.printStackTrace();
		}
		return result;
	}
	/**
	 * 根据内容类型判断文件扩展名
	 * 
	 * @param contentType 内容类型
	 * @return
	 */
	public static String getFileEndWitsh(String contentType) {
		String fileEndWitsh = "";
		if ("image/jpeg".equals(contentType))
			fileEndWitsh = ".jpg";
		else if ("audio/mpeg".equals(contentType))
			fileEndWitsh = ".mp3";
		else if ("audio/amr".equals(contentType))
			fileEndWitsh = ".amr";
		else if ("video/mp4".equals(contentType))
			fileEndWitsh = ".mp4";
		else if ("video/mpeg4".equals(contentType))
			fileEndWitsh = ".mp4";
		return fileEndWitsh;
	}
	/**
	 * 数据提交与请求通用方法
	 * @param access_token 凭证
	 * @param RequestMt 请求方式
	 * @param RequestURL 请求地址
	 * @param outstr 提交json数据
	 * */
    public static int PostMessage(String access_token ,String RequestMt , String RequestURL , String outstr){
    	int result = 0;
    	RequestURL = RequestURL.replace("ACCESS_TOKEN", access_token);
    	Map jsonobject = HttpRequest(RequestURL+"&debug=1", RequestMt, outstr);
    	 if (null != jsonobject) {  
 	        if (0 !=CommonUtils.getInt(jsonobject.get("errcode")+"")) {  
 	            result = CommonUtils.getInt(jsonobject.get("errcode")+"");  
 	            String error = "errcode:{"+jsonobject.get("errcode")+"} errmsg:{"+jsonobject.get("errmsg")+"}";  
				if (logger.isInfoEnabled()) {
					logger.info("PostMessage(String, String, String, String)"+error);
				}
 	        }  
 	    }
      
		if (logger.isDebugEnabled()) {
			logger.debug("PostMessage(String, String, String, String) - 返回数据"+RequestURL+outstr);
		}
    	return result;
    }
}  

